// Learn TypeScript:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/life-cycle-callbacks.html

import EventManager from "../manager/EventManager";
import UnitManager from "../manager/UnitManager";
import MapUtil from "../map/MapUtil";
import UnitNode from "../unit/UnitNode";

const {ccclass, property} = cc._decorator;

@ccclass
export default class UnitList extends cc.Component {

    @property(cc.Prefab)
    unitPrefab: cc.Prefab = null;
    @property(cc.Prefab)
    unitPrefab2: cc.Prefab = null;
    @property(cc.Prefab)
    unitPrefab3: cc.Prefab = null;

    public curr_UnitNode: cc.Node = null;
    unitNodes = new Map();

    // LIFE-CYCLE CALLBACKS:
    setUnit () {
        EventManager.Inst.on("UnitNode-TagonClick",this,this.TagonClick)
        UnitManager.Inst.generateUnitNodes(5);
        let i = 0
        UnitManager.Inst.unitNodes.forEach((unit,key) => {
            let t_unitNode = i >2?cc.instantiate(this.unitPrefab2):cc.instantiate(this.unitPrefab)
            if (i == 3) {
                t_unitNode = cc.instantiate(this.unitPrefab3)
            }
            t_unitNode.getComponent(UnitNode).uid = unit.uid
            t_unitNode.getComponent(UnitNode).setName(unit.name)
            let t_pos = MapUtil.mapCellToPixelPoint(cc.v2(10,9+i));
            t_unitNode.setPosition(t_pos.x,t_pos.y)
            t_unitNode.parent = this.node
            this.unitNodes.set(unit.uid,t_unitNode)
            i += 1
        });
    }

    TagonClick(uid){
        if (this.curr_UnitNode) {
            this.curr_UnitNode.getComponent(UnitNode).cancelToggle();
            this.curr_UnitNode.zIndex
        }
        this.curr_UnitNode = this.getUnitNodeByUid(uid);
        EventManager.Inst.emit("UnitNode-ShowMoveRange");
    }

    getUnitNodeByUid(uid){
        let unitNode = this.unitNodes.get(uid)
        
        return unitNode?unitNode:null
    }



    update (dt) {
        //排序
        this.unitNodes.forEach(unit => {
            unit.zIndex = -unit.y
        });
    }
}
